import { Dialogue, getDialoguePage, Message } from '@/services/MessageService'
import { makeAutoObservable } from 'mobx'

class SessionMessage {
  toUserId?: string = 'ss'
  toOpenId?: string
  appId?: string
  content?: string

  currentDialogueId?: string
  messageList: Message[] = []
  current: number = 0
  pageSize: number = 5
  pages: number = 0

  setToUserId = (toUserId: string) => {
    this.toUserId = toUserId
  }
  setToOpenId = (toOpenId: string) => {
    this.toOpenId = toOpenId
  }
  setAppId = (appId: string) => {
    this.appId = appId
  }
  setContent = (content: string) => {
    this.content = content
  }

  setCurrent = (current: number) => {
    this.current = current
  }

  setPageSize = (pageSize: number) => {
    this.pageSize = pageSize
  }

  changeChat = (dialogue: Dialogue) => {
    this.setToOpenId(dialogue.user.openid)
    this.setAppId(dialogue.user.appId)
    this.currentDialogueId = dialogue.id
    this.current = 0
    this.pages = 2
    this.messageList = []
    this.flushChatData().then()

    // runInAction(() => {})
  }

  flushChatData = async () => {
    if (!this.hasMore) {
      return
    }
    this.current++
    const pageData = await getDialoguePage({
      current: this.current,
      pageSize: this.pageSize,
      dialogueId: this.currentDialogueId || '',
    })

    this.pages = pageData.pages
    this.messageList.push(...pageData.data)
    console.log(`请求第${this.current}页数据 --> ${JSON.stringify(pageData)}`)
  }

  get hasMore() {
    return this.current < this.pages
  }
  constructor() {
    makeAutoObservable(this, {}, { autoBind: true })
  }
}

export default SessionMessage
export const sessionMessage = new SessionMessage()
